import Vue from 'vue'
import Vuex from 'vuex'
import { getQuery } from '@/utils/index.js'
Vue.use(Vuex)

const TOKENKEY = 'XIAOSHUBAO-TOKEN'
const systemInfo = uni.getSystemInfoSync()
console.log('systemInfo:', systemInfo)

let isH5 = false
let isH5Test = false
let isWeixin = false
let appId = ''
let runtime = 1

console.log(process.env, 'process')

// #ifdef H5
// 增加H5跳转H5参数：开启：isTest=1, 默认isH5=ture
isH5 = true
isH5Test = ['localhost', 'test-m.bendiclass.com'].includes(window.location.hostname)
appId = 'wx6223f311b532c11d'
runtime = getRuntimeValue()
console.log('runtime: ', runtime)
// #endif

// #ifdef MP-WEIXIN
isWeixin = true
appId = 'wx47b74cca2932cd6d'
// #endif

const userInfo = uni.getStorageSync('userInfo') || {}
userInfo.phone = ''

const store = new Vuex.Store({
  state: {
    wxSdkReady: true,
    isRedirect: false, // 处理接口600等code码
    appId,
    wxCode: uni.getStorageSync('wxCode') || '',
    miniProgramLoginCode: '',
    isSharePage: 0, // 1分享 0正常
    token: uni.getStorageSync(TOKENKEY) || '',
    systemInfo: {
      windowHeight: systemInfo.windowHeight,
      screenHeight: systemInfo.screenHeight,
      screenWidth: systemInfo.screenWidth,
      uniBarHeight: 44,
      topBarHeight: systemInfo.statusBarHeight + 44,
      statusBarHeight: systemInfo.statusBarHeight,
      platform: systemInfo.platform, // 客户端平台，值域为：ios、android
      system: systemInfo.system, // 操作系统版本
      brand: systemInfo.brand, // 手机品牌
      model: systemInfo.model, // 手机型号
      iosSystemVersion: getIosSystemVersion(),
      netWorkType: ''
    },
    env: {
      isDev: process.env.NODE_ENV === 'development',
      isAndroid: systemInfo.system.includes('Android') || systemInfo.system.includes('Other'),
      isIos: systemInfo.system.includes('iOS'), // @todo 注意H5不用分 安卓和iOS
      isH5,
      isH5Test, // 只包含H5
      isWeixin,
      isTest: process.env.NODE_ENV === 'development' || isH5Test, // 包含H5和微信
      runtime // 1方便测试调式入口 2. 不弹起跳小程序(0不跳， 1跳)
    },
    // 用户的基本信息 phone 必须
    userInfo: userInfo,
    // 书籍信息
    bookId: ''
  },
  mutations: {
    setMiniProgramLoginCode (state, code) {
      state.miniProgramLoginCode = code
    },
    // 更新token
    setToken (state, token) {
      state.token = token
      if (token) {
        uni.setStorage({ key: TOKENKEY, data: token })
      } else {
        // 退出时清除token
        uni.removeStorage({ key: TOKENKEY })
      }
    },

    setSharePage (state, value) {
      state.isSharePage = Number(value) || 0
    },
    // 更新用户信息
    setUserInfo (state, userInfo) {
      console.log(3333333333, userInfo)
      state.userInfo = { ...state.userInfo, ...userInfo }
      uni.setStorageSync('userInfo', { grade: userInfo.grade, gradeName: userInfo.gradeName, identity: userInfo.identity })
    },
    setUserInfoPhone (state, userInfoPhone) {
      state.userInfo.phone = userInfoPhone
    },
    setBookId (state, bookId) {
      state.bookId = bookId
    },
    setStudyPackage (state, res) {
      state.studyPackage = res
    },
    setStudyPackageProp (state, payload) {
      state.studyPackage = { ...state.studyPackage, ...payload }
    },
    setRuntime (state, val) {
      state.env.runtime = val
    }
  },
  actions: {
    updateBookId (context, bookId) {
      context.commit('setBookId', bookId)
    },
    updateBookScene (context, bookId) {
      uni.flux.$api.book.getBookScene(bookId).then((res) => {
        if (res) {
          context.commit('setBookScene', res.scene)
          context.commit('setFreeTimes', res.freeTimes)
        }
      })
    }
  }
})
export default store

/**
 * 处理ios不支持webp问题
 * @returns {string|number}
 */
function getIosSystemVersion () {
  // system: "iOS 14.4.1"
  if (systemInfo.platform === 'devtools') {
    return 14
  }
  if (systemInfo.platform === 'ios') {
    const versions = systemInfo.system.split(' ')
    if (versions && versions.length > 2) {
      console.log(versions[1].split('.')[0])
      return versions[1].split('.')[0]
    } else {
      return 0
    }
  }
  return 0
}

function getRuntimeValue () {
  if (getQuery('runtime') === '0') {
    return 0
  }
  return 1
}
